<template>
  <div style="padding: 0 17px">
    <Breadcrumb/>
    <div style="margin-top: 20px">
      <el-button type="primary" style="margin-right: 15px" @click="addItem">新增</el-button>
      <el-select
          @change="load"
          v-model="this.selectedState"
          placeholder="选择法规"
          style="width: 150px;margin-right: 15px"
          clearable
      >
        <el-option
            v-for="item in stateOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value"
        />
      </el-select>
      颁布日期
      <el-date-picker
          style="width: 250px"
          v-model="searchData1"
          type="daterange"
          range-separator="到"
          start-placeholder="开始时间"
          end-placeholder="结束时间"
          value-format="YYYY-MM-DD"
      />
      实施日期
      <el-date-picker
          style="width: 250px"
          v-model="searchData2"
          type="daterange"
          range-separator="到"
          start-placeholder="开始时间"
          end-placeholder="结束时间"
          value-format="YYYY-MM-DD"
      />
      <el-input v-model="keyWord" placeholder="法规名称/机关/文号"
                style="width: 150px;height: 33px;margin-right: 10px;margin-left: 10px;font-size: 13px;" clearable></el-input>
      <el-button type="primary" style="color: #fff;font-size: 12px;background-color: #1890ff;" @click="load">搜索
      </el-button>
      <el-button type="success" style="" @click="importData">导入</el-button>
      <el-button type="success" style="" @click="exportData">导出</el-button>
    </div>
    <div>
      <el-table :data="tableData"  border style="width: calc(100vw - 240px);margin-top: 20px;height: 70vh;color: #909399;font-size: 15px;">
        <el-table-column prop="id" label="ID" width="100"/>
        <el-table-column prop="lawsName" label="法规名称" width="350"/>
        <el-table-column prop="lawsType" label="法规类别" align="center" width="250">
          <template #default="scope">
            <tag v-if="scope.row.lawsType === '0'">消防基本法</tag>
            <tag v-else-if="scope.row.lawsType === '1'">消防行政法规</tag>
            <tag v-else-if="scope.row.lawsType === '2'">消防技术法规</tag>
          </template>
        </el-table-column>
        <el-table-column prop="promulgatAuthor" label="颁布机关" width="350"/>
        <el-table-column prop="approvalAuthor" label="批准机关" width="350"/>
        <el-table-column prop="promulgatNumber" label="颁布文号" width="350"/>
        <el-table-column prop="enactmentDate" label="颁布日期" width="200"/>
        <el-table-column prop="materialDate" label="实施日期" width="200"/>
        <el-table-column align="center" label="操作" fixed="right" width="180">
          <template v-slot="scope">
            <el-button type="primary" size="small" icon="Edit" @click="editItem(scope.row)">编辑</el-button>
            <el-button type="primary" size="small" icon="Edit" @click="openFile(scope.row.fileUrl)">查看
            </el-button>
            <el-button v-if="this.userInformation.role === 1" type="danger" size="small" icon="Delete" @click="deleteItem(scope.row.id)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <el-pagination
          :current-page="currentPage"
          :page-size="pageSize"
          :page-sizes="[10, 20, 30, 50]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          :background="true"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
      />
    </div>
    <el-dialog :close-on-click-modal="false" v-model="operationItemDialog" title="基本信息" width="700">
      <el-form :model="form" :rules="rules" ref="form" label-position="right" class="demo-roleForm">
        <el-form-item label="法规名称" prop="lawsName">
          <el-input v-model="form.lawsName" class="input-size" placeholder="类型名称"></el-input>
        </el-form-item>
        <el-form-item label="法规类别" prop="lawsType">
          <el-select
              v-model="form.lawsType"
              placeholder="选择法规"
              style="width: 150px;margin-right: 15px"
              clearable
          >
            <el-option
                v-for="item in stateOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="颁布机关" prop="promulgatAuthor">
          <el-input v-model="form.promulgatAuthor" class="input-size"></el-input>
        </el-form-item>
        <el-form-item label="批准机关" prop="approvalAuthor">
          <el-input v-model="form.approvalAuthor" class="input-size"></el-input>
        </el-form-item>
        <el-form-item label="颁布文号" prop="promulgatNumber">
          <el-input v-model="form.promulgatNumber" class="input-size"></el-input>
        </el-form-item>
        <el-form-item label="颁布日期" prop="enactmentDate">
          <el-date-picker
                  v-model="form.enactmentDate"
                  type="date"
                  value-format="YYYY-MM-DD HH:mm:ss"
                  placeholder="颁布日期">
          </el-date-picker>
        </el-form-item>

        <el-form-item label="实施日期" prop="materialDate">
          <el-date-picker
                  v-model="form.materialDate"
                  type="date"
                  value-format="YYYY-MM-DD HH:mm:ss"
                  placeholder="实施日期">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="输入人姓名" prop="enterName">
          <el-input v-model="form.enterName" class="input-size"></el-input>
        </el-form-item>
        <el-form-item label="法规文件" prop="fileUrl">
          <el-upload
                  :before-upload="checkFileType"
                  class="avatar-uploader"
                  :action="'/api/files/upload'"
                  :on-success="photoHandleSuccess"
                  :on-error="photoHandleError"
                  :show-file-list="true"
          >
            <template #tip>
              <div class="el-upload__tip">
                {{ photoType() }}文件应小于{{ fileSizeLimit() }}
              </div>
            </template>
            <el-button size="small" type="primary">上传</el-button>
            <el-button size="small" type="danger" v-if="form.fileUrl" @click="deleteImage">删除</el-button>
          </el-upload>
        </el-form-item>
        <el-form-item>
          <el-button style="font-size: 12px" type="primary" @click="submitForm('form')">提交</el-button>
          <el-button style="font-size: 12px;color: #606266" @click="reset('form')">取消</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
    <el-dialog title="导入" v-model="dialogImportVisible" width="520px">
      <el-form label-position="right" label-width="100px">
        <el-form-item label="模板下载:" padding-top:10px>
          <el-button type="primary" size="small" style="" @click="exportTemplate">消防法规</el-button>
        </el-form-item>
        <el-form-item label="文件" padding-top:-20px>
          <el-upload :headers="headers"
                           :multiple="false"
                     :on-success="onUploadSuccess"
                     :on-error="onUploadError"
                     :action="serverIp+'/fire-laws/importData'"
                     class="upload-demo">
            <el-button size="small" type="primary">点击上传</el-button>
            <div slot="tip" class="el-upload__tip">只能上传xlsx文件</div>
          </el-upload>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogImportVisible = false">取消</el-button>
      </div>
    </el-dialog>
    <el-dialog title="文件预览" v-model="openItemFileDialog" width="70%" append-to-body center>
      <iframe :src="pdfSrc" frameborder="0" style="background-color: #fff;width: 100%; height: 600px"></iframe>
      <div slot="footer" class="dialog-footer">
        <el-button @click="openItemFileDialog = false">取消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import request from "@/utils/request.js";
import Breadcrumb from "@/components/Breadcrumb.vue";
import {serverIp} from "../../../public/static/config"
import {fileSizeLimit, photoType} from "@/assets/globalJS.js";

export default {
  name: "FireLaws",
  components: {Breadcrumb},
  data() {
    return{
      pdfSrc: '',
      openItemFileDialog: false,
      serverIp,
                headers: {
                    token:  JSON.parse(localStorage.getItem('user')).token,
                },
      dialogImportVisible: false,
      operationItemDialog: false,
      userInformation:JSON.parse(localStorage.getItem("user")),
      tableData:[],
      search:"",
      selectedState:'',
      stateOptions:[
        {
          value:"0",
          label:"消防基本法"
        },{
          value:"1",
          label:"消防行政法规"
        },{
          value:"2",
          label:"消防技术法规"
        }
      ],
      searchData1:[],
      searchData2:[],
      rules: {
        lawsName: [
          {required: true, message: '请输入法规名称', trigger: 'blur'},
        ],
      },
      form:{},
      currentPage: 1,
      pageSize: 10,
      total: 10,
    }
  },
  created() {
    this.load()
  },
  methods: {
    importData() {
      this.dialogImportVisible = true;
    },
    onUploadSuccess() {
      this.$message.success('上传成功');
      this.dialogImportVisible = false;
      location.reload();
    },
    onUploadError(){
      this.$message.error('上传失败');
    },
    // 模板下载
    exportTemplate() {
      window.location.href = '../xlsx/fireLaws.xlsx'
    },
    exportData() {
      if (this.keyWord===undefined){
        this.keyWord=""
      }
      let enactStartTime="", enactEndTime=""
      if (this.searchData1!==null&&this.searchData1.length!==0){
        enactStartTime=this.searchData1[0]
        enactEndTime=this.searchData1[1]
      }
      let materialStartTime="", materialEndTime=""
      if (this.searchData2!==null&&this.searchData2.length!==0){
        materialStartTime=this.searchData2[0]
        materialEndTime=this.searchData2[1]
      }
      window.open(serverIp + '/fire-laws/export?keyWord='+this.keyWord+"&enactStartTime="+enactStartTime+"&enactEndTime="+enactEndTime+"&materialStartTime="+materialStartTime+"&materialEndTime="+materialEndTime);
    },
    // 添加
    addItem(){
      this.operationItemDialog = true;
    },
    // 编辑
    async editItem(scope) {
      Object.assign(this.form, scope)
      this.operationItemDialog = true
    },
    // 提交
    submitForm(val){
      this.$refs[val].validate((valid) => {
        if (valid) {
          request.post("/fire-laws/edit",this.form).then(res=>{
            if (res.code==='200'){
              this.operationItemDialog=false
              this.$message({
                message:"成功",
                type:"success"
              })
              this.load()
            }else {
              this.$message.error("操作失败"+res.msg)
            }
          })
        }
      })
    },
    // 取消
    reset(val){
      this.operationItemDialog = false;
      this.form={};
      this.$refs[val].resetFields();
    },
    handleSizeChange(pageSize) {   // 改变当前每页的个数触发
      this.pageSize = pageSize
      this.load()
    },
    handleCurrentChange(pageNum) {  // 改变当前页码触发
      this.currentPage = pageNum
      this.load()
    },
    // 删除
    deleteItem(scope){
      this.$confirm('是否确定删除?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        request.get("/fire-laws/delete/"+scope).then(res=>{
          if (res.code==='200'){
            this.$message.success("成功")
            this.load()
          }else {
            this.$message.error("删除失败，"+res.msg)
          }
        })
      });
    },
    // 搜索及初始化
    load(){
      if (this.keyWord===undefined){
        this.keyWord=""
      }
      let enactStartTime="", enactEndTime=""
      if (this.searchData1!==null&&this.searchData1.length!==0){
        enactStartTime=this.searchData1[0]
        enactEndTime=this.searchData1[1]
      }
      let materialStartTime="", materialEndTime=""
      if (this.searchData2!==null&&this.searchData2.length!==0){
        materialStartTime=this.searchData2[0]
        materialEndTime=this.searchData2[1]
      }
      request.get("/fire-laws/page?pageNum=" + this.currentPage + "&pageSize=" + this.pageSize+"&keyWord="+this.keyWord+"&enactStartTime="+enactStartTime+"&enactEndTime="+enactEndTime+"&materialStartTime="+materialStartTime+"&materialEndTime="+materialEndTime).then(res => {
        if (res.code === '200') {
          for (let key in res.data) {
            if (key === "records") {
              this.tableData = res.data[key];
            } else if (key === "total") {
              this.total = res.data[key];
            }
          }
        } else {
          this.$message.error("错误"+res.msg)
        }
      })
    },
    checkFileType(file) {
      const fileName = file.name
      const fileType = fileName.substring(fileName.lastIndexOf('.'))
      // '.xbm','.tif','pjp','.svgz','jpg','jpeg','ico','tiff','.gif','svg','.jfif','.webp','.png','.bmp','pjpeg','.avif'
      if (
              fileType === '.pdf' ||
              fileType === '.txt' ||
              fileType === '.xbm' ||
              fileType === '.tif' ||
              fileType === '.pjp' ||
              fileType === '.svgz' ||
              fileType === '.jpg' ||
              fileType === '.jpeg' ||
              fileType === '.ico' ||
              fileType === '.tiff' ||
              fileType === '.gif' ||
              fileType === '.svg' ||
              fileType === '.jfif' ||
              fileType === '.webp' ||
              fileType === '.png' ||
              fileType === '.bmp' ||
              fileType === '.pjpeg' ||
              fileType === '.avif'
      ) {
        // 不处理
      } else {
        this.$message.error(
                '不是正确的格式文件,请上传正确的文件类型'
        )
        return false
      }
    },
    photoHandleSuccess(response) {
      this.form.fileUrl = `/api/file/download${response}`
      this.$message.success('上传成功');
    },
    photoType() {
      return "pdf,txt," + photoType
    },
    fileSizeLimit() {
      return "100MB"
    },
    photoHandleError() {
      this.$message.error("上传文件大小请勿超过100MB")
    },
    deleteImage() {
      this.form.fileUrl = '';
      this.$message.success('删除成功');
    },
    openFile(scope) {
      this.openItemFileDialog = true;
      this.pdfSrc = scope;
    }
  }
}
</script>

<style scoped>
:deep(.el-table th .cell)  {
  font-weight: 700
}
:deep(.el-form-item__label) {
  font-size: 14px;
  font-weight: 700
}
.input-size {
  font-size: 14px;
}
</style>
